package net.beaconcontroller.comp416project.model;

import org.openflow.util.U8;
/**
 * 
 * @author SHI ZHONGQI 10836265D from HK PolyU
 * @author JI ZHIHAO 13022865X from HK PolyU
 * Modifyed from the HexString provided by Beacon
 */
public class HexIPString {


	public static String toIp(int ip, int prefix){
		  String str;
		 
	        if (prefix >= 32) {
	            str = ipToString(ip);
	        } else {
	            // use the negation of mask to fake endian magic
	            int mask = ~((1 << (32 - prefix)) - 1);
	            str = ipToString(ip & mask) + "/" + prefix;
	        }

	        return str;
	}
	
    public static String ipToString(int ip) {
        return Integer.toString(U8.f((byte) ((ip & 0xff000000) >> 24))) + "."
                + Integer.toString((ip & 0x00ff0000) >> 16) + "."
                + Integer.toString((ip & 0x0000ff00) >> 8) + "."
                + Integer.toString(ip & 0x000000ff);
    }


    /**
     * Convert a string of bytes to a ':' separated hex string
     * @param bytes
     * @return "0f:ca:fe:de:ad:be:ef"
     */
    public static String toHexString(byte[] bytes) {
        int i;
        String ret = "";
        String tmp;
        for(i=0; i< bytes.length; i++) {
            if(i> 0)
                ret += ":";
            tmp = Integer.toHexString(U8.f(bytes[i]));
            if (tmp.length() == 1)
                ret += "0";
            ret += tmp; 
        }
        return ret;
    }
    
    public static String toHexString(long val) {
        char arr[] = Long.toHexString(val).toCharArray();
        String ret = "";
        // prepend the right number of leading zeros
        int i = 0;
        for (; i < (16 - arr.length); i++) {
            ret += "0";
            if ((i % 2) == 1)
                ret += ":";
        }
        for (int j = 0; j < arr.length; j++) {
            ret += arr[j];
            if ((((i + j) % 2) == 1) && (j < (arr.length - 1)))
                ret += ":";
        }
        return ret;
    }
    
    
    public static int fromIPString(String value){
    	String[] objects = value.split("\\.");
    	int a=0;
    	a+=Integer.parseInt(objects[0])*Math.pow(2, 24);
    	a+=Integer.parseInt(objects[1])*Math.pow(2, 16);
    	a+=Integer.parseInt(objects[2])*Math.pow(2, 8);
    	a+=Integer.parseInt(objects[3]);
    	
    	return a;
    }
    
    /**
     * Convert a string of hex values into a string of bytes
     * @param values "0f:ca:fe:de:ad:be:ef"
     * @return [15, 5 ,2, 5, 17] 
     */
    
    public static byte[] fromHexString(String values) {
        String[] octets = values.split(":");
        byte[] ret = new byte[octets.length];
        int i;
        
        for(i=0;i<octets.length; i++)
            ret[i] = Integer.valueOf(octets[i], 16).byteValue();
        return ret;
    }
    
    public static long toLong(String values) {
        return Long.parseLong(values.replaceAll(":", ""),16);
    }

}
